import { GooBaseGoodsSpecification } from '../../../goo-base-goods-specification/goo-base-goods-specification.type';
import {Component, OnInit} from '@angular/core';
import {AddBaseGoodsComponent} from '../add-base-goods.component';
import {ErrRes} from '../../../../../frame/global/err-res';
import {BaseGoods} from '../../base-goods.type';
import {Services} from '../../../../../frame/module/services';
import {HttpRequestClient} from '../../../../../frame/http-request-client/http-request-client';
import {UrlRou} from '../../../../../frame';
import {Zero3Alert} from '../../../../../frame/global/zero3-alert/zero3-alert.component';
import * as fa from '@fortawesome/free-solid-svg-icons';
import {FroalaEditor} from '../../../../../frame/global/froala-editor';
import {GooTypeLevel1Condition} from '../../../goo-type-level1/goo-type-level1.type';
import {isNullOrUndefined} from 'util';
import {GooTypeLevel2Condition} from '../../../goo-type-level2/goo-type-level2.type';
import {GooBrandCondition} from '../../../goo-brand/goo-brand.type';
import {filter, map} from 'rxjs/operators';
import {GooAttributeValueCondition} from '../../../goo-attribute-value/goo-attribute-value.type';
import {GooBaseGoodsAttribute} from '../../../goo-base-goods-attribute/goo-base-goods-attribute.type';
import {GooBaseGoodsAttributeValue} from '../../../goo-base-goods-attribute-value/goo-base-goods-attribute-value.type';
import { FileUploader } from 'ng2-file-upload';

@Component({
    selector: 'app-main-add-base-goods',
    templateUrl: './main-add-base-goods.component.html',
    styleUrls: ['./main-add-base-goods.component.css']
})
export class MainAddBaseGoodsComponent implements OnInit {

    froalaEditorOptions = Object.assign(FroalaEditor.options, {});

    errRes = new ErrRes();

    domain = new BaseGoods();

    ossMap = new Map<number, any>();

    selectedAttributes = new Map<string, GooBaseGoodsAttribute>();
    selectedAttribute: any;
    selectedAttributeValues = [];
    selectedAttributeValueUUIDS = [];
    // 生成的规格列表
    specs: any = [];
    func = {
        updateSpecImg: (index) => {
                this.ossMap.get(index).uploadFile((response, status) => {
                    if (status === 200) {
                        const fileUrl = JSON.parse(response).detail.fileUrl;
                        this.specs[index].serSpecImg = fileUrl;
                    } else {
                        const fileUrl = '';
                        this.specs[index].serSpecImg = fileUrl;
                    }
                });
        },
        save: {
            req: (event) => {
                console.log(this.domain);
                console.log(this.selectedAttributes);
                if (this.selectedAttributes.size === 0) {
                    return;
                }
                const gooBaseGoodsAttributeList: {
                    fkGooAttributeUUID: string,
                    name: string,
                    serOrder: string,
                    gooBaseGoodsAttributeValueList: {
                        fkGooAttributeValueUUID: string,
                        name: string
                    }[]
                }[] = [];
                if (this.specs.length === 0 ) {
                    Zero3Alert.req('请先点击生成规格按钮生成规格');
                    return;
                }
                this.selectedAttributes.forEach((value, key) => {
                    const gooBaseGoodsAttributeValueList: {}[] = Array.from(value['gooBaseGoodsAttributeValueList']) || [];
                    const attrValUUIDList: {
                        fkGooAttributeValueUUID: string,
                        name: string
                    }[] = gooBaseGoodsAttributeValueList.map((item: GooBaseGoodsAttributeValue) => {
                        return {fkGooAttributeValueUUID: item.fkGooAttributeValueUUID, name: item.name};
                    });
                    gooBaseGoodsAttributeList.push({
                        fkGooAttributeUUID: key,
                        name: value.name,
                        serOrder: value.serOrder,
                        gooBaseGoodsAttributeValueList: attrValUUIDList
                    });
                });
                console.log(gooBaseGoodsAttributeList);
                //
                const gooBaseGoods = Object.assign({
                    gooBaseGoodsAttributeList: gooBaseGoodsAttributeList,
                    specifications: this.specs
                }, this.domain);
                console.log(gooBaseGoods);
                Services.baseGoods.transactionSave(gooBaseGoods, this.func.save.callback).subscribe();
            },
            callback: {
                success: (result) => {
                    HttpRequestClient.router.navigate([UrlRou.baseGoods.list]);
                },
                error: (result) => {
                    this.errRes.error = result.error;
                    this.errRes.statusText = result.statusText;
                }
            },
        },
        addAttribute: () => {
            if (!isNullOrUndefined(this.selectedAttribute) && this.selectedAttributeValues.length > 0) {
                const attribute = new GooBaseGoodsAttribute();
                attribute.name = this.selectedAttribute.name;
                attribute.fkGooAttributeUUID = this.selectedAttribute.id;
                attribute.fkBaseGoodsUUID = this.domain.uuid;
                attribute.serOrder = '0';
                attribute['gooBaseGoodsAttributeValueList'] = [];
                this.selectedAttributeValues.forEach(item => {
                    const value = new GooBaseGoodsAttributeValue();
                    value.name = item.name;
                    value.fkGooAttributeValueUUID = item.id;
                    attribute['gooBaseGoodsAttributeValueList'].push(value);
                });
                this.selectedAttributes.set(attribute.fkGooAttributeUUID, attribute);
            }
        },

        // 根据选择的属性创建规格
        createSpecs: () => {
                // 规格
                this.specs = [];
                const attrs = Array.from(this.selectedAttributes.values());
                const newAttVals = attrs
                .sort((a, b) => parseInt(a.serOrder, 10)  - parseInt(b.serOrder, 10))
                .map(item => Array.from(item['gooBaseGoodsAttributeValueList']));
                const result = [[]];
                newAttVals.forEach(gooBaseGoodsAttributeValues => {
                    const p = [];
                    result.forEach(r => {
                        p.push(Array.from(r));
                    });
                    gooBaseGoodsAttributeValues.forEach((element, index) => {
                        if (index > 0 && p.length > 0) {
                            p.forEach(i => {
                                result.push(i);
                            });
                        }
                        if (p.length > 0) {
                            p.forEach((j, jIndex) => {
                                result[index * p.length + jIndex].push(element);
                            });
                        } else {
                            result.push([element]);
                        }
                    });
                });
                console.log(result);
                result.forEach(item => {
                    if (item.length > 0) {
                        const spec: any = {};
                        const name = item.map(i => i.name).join(' ');
                        spec.serName = name;
                        spec['goodsSpecificationValues'] = item;
                        this.specs.push(spec);
                    }
                });
                console.log(this.specs);
                // 规格结束
        },

        deleteAttributeValue: (fkGooAttributeUUID, fkGooAttributeValueUUID) => {
            const values: GooBaseGoodsAttributeValue[] = this.selectedAttributes.get(fkGooAttributeUUID)['gooBaseGoodsAttributeValueList'];
            const result = values.filter(item => item.fkGooAttributeValueUUID !== fkGooAttributeValueUUID);
            if (result.length > 0) {
                this.selectedAttributes.get(fkGooAttributeUUID)['gooBaseGoodsAttributeValueList'] = result;
            } else {
                this.selectedAttributes.delete(fkGooAttributeUUID);
            }
        },

        deleteAttribute: (item) => {
            this.selectedAttributes.delete(item);
        },
        deleteSpec: (index) => {
            this.specs.splice(index, 1);
        },
        loadData: () => {
            Services.gooAttribute.list()
                .pipe(filter(item => !isNullOrUndefined(item) && item.code === 'success'),
                    map(item => {
                        const result = [];
                        item.page.content.forEach(base => {
                            result.push({id: base.uuid, name: base.name});
                        });
                        return result;
                    }))
                .subscribe(result => {
                    this.extend.domain.gooAttribute.items = result;
                });
        },
        loadAttributeValue: (upper) => {
            const condition = new GooAttributeValueCondition();
            condition.upper = upper;
            Services.gooAttributeValue.list(condition)
                .pipe(filter(item => !isNullOrUndefined(item) && item.code === 'success'),
                    map(item => {
                        const result = [];
                        item.page.content.forEach(base => {
                            result.push({id: base.uuid, name: base.name});
                        });
                        return result;
                    }))
                .subscribe(result => {
                    this.extend.domain.gooAttributeValue.items = result;
                });
        }
    };
    extend = {
        domain: {
            gooAttribute: {
                items: [],
                nickname: '商品属性',
                change: (event) => {
                    console.log(event);
                    this.extend.domain.gooAttributeValue.items = [];
                    this.selectedAttributeValues = [];
                    this.selectedAttributeValueUUIDS = [];
                    this.selectedAttribute = event;
                    if (!isNullOrUndefined(event)) {
                        this.func.loadAttributeValue(event.id);
                    }

                }

            },
            gooAttributeValue: {
                items: [],
                nickname: '商品属性值',
                change: (event) => {
                    console.log(event);
                    this.selectedAttributeValues = event;
                }
            },
            serLevel1: {
                items: [],
                icon: fa.faSearchPlus,
                nickname: '一级分类类型',
                change: (event) => {
                    console.log(event);
                }
            },
            serLevel2: {
                items: [],
                icon: fa.faSearchPlus,
                nickname: '二级分类类型',
                change: (event) => {
                    console.log(event);
                }
            },
            serBrand: {
                items: [],
                icon: fa.faSearchPlus,
                nickname: '品牌',
                change: (event) => {
                    console.log(event);
                }
            },
            default: () => {
                this.domain.serAudit = 'WAIT_SUBMIT';
                this.domain.serUsing = 'ENABLE';
                this.domain.serShelfState = 'ON';
                this.domain.serGoodsJifen = 'YESSEND';
                this.domain.serGoodsNew = 'NO';
                this.domain.serGoodsIsactive = 'NOSEND';
            },
            serAudit: () => {
                return 'serAudit';
            },
            serGoodsStartTime: {
                icon: fa.faCalendar,
                nickname: '打折开始时间',
                value: () => {
                    // return `${this.condition.createTimeOUTSET} - ${this.condition.createTimeFINISH}`;
                    return this.domain.serGoodsStartTime;
                },
                focus: (event) => {
                    this.domain.serGoodsStartTime = event.target.value;
                },
                blur: (event) => {
                }
            },
            serGoodsEndTime: {
                icon: fa.faCalendar,
                nickname: '打折结束时间',
                value: () => {
                    // return `${this.condition.createTimeOUTSET} - ${this.condition.createTimeFINISH}`;
                    return this.domain.serGoodsEndTime;
                },
                focus: (event) => {
                    this.domain.serGoodsEndTime = event.target.value;
                },
                blur: (event) => {
                }
            },
            fileSerGoodsP1: {
                oss: Services.aliOSS.simple(),
                change: (event) => {
                    console.log(event.target.value); // file name
                    this.extend.domain.fileSerGoodsP1.oss.uploadFile((response, status, headers) => {
                        if (status === 200) {
                            this.extend.domain.fileSerGoodsP1.oss.fileUrl = JSON.parse(response).detail.fileUrl;
                            this.domain.serGoodsP1 = this.extend.domain.fileSerGoodsP1.oss.fileUrl;
                        } else {
                            this.extend.domain.fileSerGoodsP1.oss.fileUrl = '';
                            this.domain.serGoodsP1 = this.extend.domain.fileSerGoodsP1.oss.fileUrl;
                            Zero3Alert.req('fail');
                        }
                    });
                }
            },
            fileSerGoodsP2: {
                oss: Services.aliOSS.simple(),
                change: (event) => {
                    console.log(event.target.value); // file name
                    this.extend.domain.fileSerGoodsP2.oss.uploadFile((response, status, headers) => {
                        if (status === 200) {
                            this.extend.domain.fileSerGoodsP2.oss.fileUrl = JSON.parse(response).detail.fileUrl;
                            this.domain.serGoodsP2 = this.extend.domain.fileSerGoodsP2.oss.fileUrl;
                        } else {
                            this.extend.domain.fileSerGoodsP2.oss.fileUrl = '';
                            this.domain.serGoodsP2 = this.extend.domain.fileSerGoodsP2.oss.fileUrl;
                            Zero3Alert.req('fail');
                        }
                    });
                }
            },
            fileSerGoodsP3: {
                oss: Services.aliOSS.simple(),
                change: (event) => {
                    console.log(event.target.value); // file name
                    this.extend.domain.fileSerGoodsP3.oss.uploadFile((response, status, headers) => {
                        if (status === 200) {
                            this.extend.domain.fileSerGoodsP3.oss.fileUrl = JSON.parse(response).detail.fileUrl;
                            this.domain.serGoodsP3 = this.extend.domain.fileSerGoodsP3.oss.fileUrl;
                        } else {
                            this.extend.domain.fileSerGoodsP3.oss.fileUrl = '';
                            this.domain.serGoodsP3 = this.extend.domain.fileSerGoodsP3.oss.fileUrl;
                            Zero3Alert.req('fail');
                        }
                    });
                }
            },
            files: {
                fileUrls: [],
                oss: Services.aliOSS.simple(),
                change: (event) => {
                    console.log(event.target.value); // file name
                    this.extend.domain.files.oss.uploadFile((response, status, headers) => {
                        if (status === 200) {
                            this.extend.domain.files.fileUrls.push(JSON.parse(response).detail.fileUrl);
                            this.extend.domain.files.oss.fileUrl = JSON.parse(response).detail.fileUrl;
                            this.domain.serGoodsBanner = this.extend.domain.files.fileUrls.toString();
                        } else {
                            this.extend.domain.files.oss.fileUrl = '';
                            this.domain.serGoodsBanner = this.extend.domain.files.fileUrls.toString();
                            Zero3Alert.req('fail');
                        }
                    });
                },
                del: {
                    click: (event, fileUrl) => {
                        const urlIndex = this.extend.domain.files.fileUrls.findIndex(item => item === fileUrl);
                        this.extend.domain.files.fileUrls.splice(urlIndex, 1);
                        this.domain.serGoodsBanner = this.extend.domain.files.fileUrls.toString();
                    }
                }
            },
        },
    };

    constructor(public addGooGoods: AddBaseGoodsComponent) {
        this.addGooGoods.main = this;
        // ng select
        this.domain.serGoodsT1 = null;
        // ng select
        this.domain.serGoodsT2 = null;
        // ng select
        this.domain.serGoodsBarndId = null;
        // int
        this.domain.serGoodsDazhe = '100';
    }

    ngOnInit() {
        this.extend.domain.default();
        Services.gooBrand.list(new GooBrandCondition(), {
            page: 0,
            size: 999,
            orders: 'createTime-desc,serNum-asc'
        }).subscribe(item => {
            if (!isNullOrUndefined(item) && item.code === 'success') {
                this.extend.domain.serBrand.items = [];
                item.page.content.forEach(brand => {
                    this.extend.domain.serBrand.items.push({id: brand.uuid, name: brand.serBarndName});
                });
            }
        });
        Services.gooTypeLevel1.list(new GooTypeLevel1Condition(), {
            page: 0,
            size: 999,
            orders: 'createTime-desc,serNum-asc'
        }).subscribe(item => {
            if (!isNullOrUndefined(item) && item.code === 'success') {
                this.extend.domain.serLevel1.items = [];
                item.page.content.forEach(level1 => {
                    this.extend.domain.serLevel1.items.push({id: level1.uuid, name: level1.serTypeName});
                });
            }
        });
        Services.gooTypeLevel2.list(new GooTypeLevel2Condition(), {
            page: 0,
            size: 999,
            orders: 'createTime-desc,serNum-asc'
        }).subscribe(item => {
            console.log(item);
            if (!isNullOrUndefined(item) && item.code === 'success') {
                this.extend.domain.serLevel2.items = [];
                item.page.content.forEach(level2 => {
                    this.extend.domain.serLevel2.items.push({id: level2.uuid, name: level2.serTypeName});
                });
            }
        });
        this.func.loadData();
    }

    createOSSUpload(index: number): {
        fileUrl: string,
        uploader: FileUploader,
        uploadFile: (onSuccess) => void
    }  {
        let oss = this.ossMap.get(index);
        if (isNullOrUndefined(oss)) {
            oss = Services.aliOSS.simple();
            this.ossMap.set(index, oss);
        }
        return oss;
    }


}
